/**
 * This component allow to register a new question.
 */
$.Controller( "AdminQuestion", {
	
	  
	question: null,
	dnaTypes: null,
		
	  init: function() {
		var me = this,
			i = 0;
		
		me.question = new Question();
		me.question.answers = [];
		
		DNA.findAll({}, function(dna) {
			me.dnaTypes = dna
			me.element.html("js/view/AdminQuestion.ejs", {question: me.question, dnaType: me.dnaTypes});
		});
		
	  },
	  
	  "#question-text change": function(el) {
		  if (el.context.value) {
			  this.question.attr('text', el.context.value);
		  }
	  },
	  
	  ".answer-text change": function(el) {
		  var newAnswerText = el.context.value,
		  	answer = el.context.attributes.role.value;
		  
		  if (newAnswerText) {
			  this.question.answers[answer].attr('text', newAnswerText);
		  }
	  },
	  
	  ".dna-amount-chooser change": function(el) {
		 var params = el.context.attributes.role.value.split(",");
		 this.question.answers[params[0]].dnaAssignments[params[1]].attr('amount', parseInt(el.context.value)); 
	  },
	  
	  ".dna-type-chooser change": function(el) {
		  var params = el.context.attributes.role.value.split(",");
		  this.question.answers[params[0]].dnaAssignments[params[1]].dna.attr('id', parseInt(el.context.value)); 
	  },
	  
	  ".dna-for-chooser change": function(el) {
		  var params = el.context.attributes.role.value.split(",");
		  this.question.answers[params[0]].dnaAssignments[params[1]].attr('presentee', el.context.value==="1"); 
	  },
	  
	  "#add-answer click": function(el) {
		  var me = this,
		  	//answerText = $('#answer-new').val(),
		  	answer = new Answer();
		  
		  answer.dnaAssignments = [];
		  me.question.answers.push(answer);
		  
		  me.element.html("js/view/AdminQuestion.ejs", {question: me.question, dnaTypes: me.dnaTypes});
	  },
	  
	  ".remove-answer click": function(el) {
		  var me = this,
		  	answer = parseInt(el.context.attributes.role.value);
		  
		  me.question.answers.splice(answer, 1)		  
		  me.element.html("js/view/AdminQuestion.ejs", {question: me.question, dnaTypes: me.dnaTypes});
	  },
	  
	  "#add-answer-dna click": function(el) {
		  var me = this;
		  
		  var dnaAssignment = new DNAAssignment();
		  
		  dnaAssignment.dna = new DNA();
		  me.question.answers[el.context.attributes.role.value].dnaAssignments.push(dnaAssignment);
		  me.element.html("js/view/AdminQuestion.ejs", {question: me.question, dnaTypes: me.dnaTypes});
	  },
	  
	  "#remove-answer-dna click": function(el) {
		  var me = this,
		  	params = el.context.attributes.role.value.split(",");
		  
		  me.question.answers[params[0]].dnaAssignments.splice(params[1],1);
		  me.element.html("js/view/AdminQuestion.ejs", {question: me.question, dnaTypes: me.dnaTypes});
	  },
	  
	  "#submit-question click": function(el) {
		  this.question.save(function (result) {
			  alert(result);
		  });
	  }

});
